# Controlling LEDs
So far everything we have seen does not involve controlling any hardware electronics using the Arduino.
We will start by writing a simple Sketch that turns on the built-in LED on the Uno board. It is the small LED labeled L
on the board.
There are two kinds of pins, digital and analog. We will not cover the analog pins for now. The digital pins mean they can be either HIGH
or LOW
. This also means we either output 5V through that pin or 0V.
A pin can be either INPUT
or OUTPUT
. If we are outputting voltage from the Arduino board to an electronic component connected to that pin, then our pin is OUTPUT
pin. If the electronic component is producing voltage through that pin, and the Arduino board is reading that voltage then the pin is INPUT
pin. The INPUT
or OUTPUT
mode is with respect to the Arduino board. If we want to connect an LED to the Arduino, we will want to output voltage from the Arduino to the LED. Therefore, the pin we connect the LED to will be in OUTPUT
mode. The digital pins can be seen on the top side of the Uno board labeled from 0 to 13.
On the Uno board, there is a built-in LED next to the L letter. This LED is connected to pin 13 internally. In the Arduino platform, if you use LED_BUILTIN
in your code, it will be translated into 13 since that is the pin for the built-in LED.
The above program turns on the built-in LED and then waits for 3 seconds.
# pinMode
In the setup function, the first thing we do is specify for each pin we are using whether that pin is going to be used as an output or input pin. We do that by calling the Arduino function pinMode(pinNumber, mode);
. The pinNumber
is the number of the pin we want to specify its mode, and the mode is whether it is OUTPUT
or INPUT
. On line 2 of the program, we are specifying that pin 13 is an output pin. This means we will be deciding if the pin has 5V or 0V. If we output 5V then the LED will turn on.
# digitalWrite
Line 7 specifies the output to be HIGH
to the LED_BUILTIN
pin. Which is the same if we use 13 instead of LED_BUILTIN
. We specify the output to a digital pin by using the Arduino function digitalWrite(pinNumber, HIGHorLOW);
.
Exercise
In the above code, can you turn the built-in LED off after 3 seconds?
# Blinking LED
We want to continuously blink the built-in LED every second. This sounds like a task for the loop function!
We can also connect LEDs other than the built-in LED to the Arduino board. In the above environment, we have 2 LEDs connected to the Arduino board on pins 9 and 10.
Homework
Modify the code above to blink the red and green LEDs with the built-in LED.